package com.example.demo.config;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class InitUtils {
    public static WebDriver webDriver ;
    public static WebDriver createDriver(){
        if(webDriver==null){
            System.setProperty("webdriver.chrome.driver", "C:\\学习使我快乐\\测试\\demo\\chromedriver-win64\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            webDriver=new ChromeDriver(options);
            webDriver.manage().timeouts().implicitlyWait(Duration.ofMillis(5));
        }
        return webDriver;
    }

    public InitUtils(String url){
        webDriver = createDriver();
        webDriver.get(url);
    }

    //截图
    public static void getImage(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HH_mm_ss_SSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String pngTime = sim2.format(System.currentTimeMillis());

        //名字
        String fileName = "./src/test/image/"+dirTime+"/"+str+"_"+pngTime+".png";

        File file = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(file,new File(fileName));
    }
}
